<template>
  <el-card shadow="hover" class="mt-20">
    <el-form>
      <el-form-item label="属性名">
        <el-input
          placeholder="请输入属性名"
          class="attr__input"
          v-model="attrFormData.attrName"
        />
      </el-form-item>
      <el-form-item>
        <!-- 
          禁用效果看属性名是否有值
            属性名有值，取boolean是true，希望不禁用，false
         -->
        <el-button
          type="primary"
          :icon="Plus"
          :disabled="!attrFormData.attrName"
          @click="addAttrValue"
        >
          添加属性值
        </el-button>
        <el-table :data="attrFormData.attrValueList" border class="mt-20">
          <el-table-column
            type="index"
            align="center"
            label="序号"
            width="60"
          />
          <el-table-column label="属性值名称">
            <template v-slot="{ row, $index }">
              <!-- 
                如果绑定一个标识，每一行数据会产生相同的变化，不行 
                
                el-input 编辑模式
                span     显示模式
              -->
              <el-input
                v-if="row.isShowEdit"
                size="small"
                ref="inputRef"
                v-model="row.valueName"
                @blur="switchShow(row, $index)"
                @keyup.enter="switchShow(row, $index)"
              />
              <div v-else @click="switchEdit(row)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ $index, row }">
              <el-popconfirm
                :title="`您确认要删除 ${row.valueName} 属性值吗?`"
                @confirm="delAttrValue($index)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    :icon="Delete"
                    size="small"
                    title="删除"
                  />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <!-- 
          禁用功能
            1. 属性名有值
            2. 至少有一个属性值，并且属性值名称有值
         -->
        <el-button type="primary" :disabled="disabled" @click="submit">
          确定
        </el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AddOrUpdateAttr",
};
</script>

<script lang="ts" setup>
import { Delete, Plus } from "@element-plus/icons-vue";
import { reactive, ref, nextTick, computed } from "vue";
import { ElMessage } from "element-plus";
import { addOrUpdateAttrApi } from "@/api/product/attr";
import { useCategoryStore } from "@/stores/category";
import { useAttrStore } from "@/stores/attr";
import type { AttrItem, AttrValueItem } from "@/api/product/model/attrModel";

const categoryStore = useCategoryStore();

// 提交
const submit = async () => {
  const data = {
    ...attrFormData,
    categoryId: categoryStore.category3Id as number, // 三级分类id
    categoryLevel: 3,
  };

  const id = attrStore.attr.id;

  // 修改请求需要携带id参数
  if (id) {
    data.id = id;
  }

  await addOrUpdateAttrApi(data);
  ElMessage.success(`${id ? "修改" : "添加"}属性成功`);
  cancel();
};

// 确定按钮禁用功能
const disabled = computed(() => {
  return (
    !attrFormData.attrName ||
    !attrFormData.attrValueList.some((attrValue) => attrValue.valueName)
  );
});

const attrStore = useAttrStore();

// 表单数据
const attrFormData = reactive<AttrItem>({
  attrName: attrStore.attr.attrName,
  attrValueList: attrStore.attr.attrValueList,
});

// 获取input的实例对象，从而调用其方法
const inputRef = ref();

// 添加属性值按钮
const addAttrValue = async () => {
  // 让table渲染一行数据，就是往数组添加一个对象
  attrFormData.attrValueList.push({
    // 添加一个标识，用来决定显示&编辑模式的切换
    isShowEdit: true,
    valueName: "",
  });
  /*
    Uncaught TypeError: Cannot read properties of undefined (reading 'focus')

    focus前面的内容是undefined

    更新是异步的
  */
  // nextTick(() => {
  //   // 让input获取焦点
  //   inputRef.value.focus();
  // });
  await nextTick();
  // 让input获取焦点
  inputRef.value.focus();
};

// 切换到显示模式
const switchShow = (row: AttrValueItem, index: number) => {
  if (!row.valueName) {
    // 如果数据为空，删除当前行数据
    attrFormData.attrValueList.splice(index, 1);
    return;
  }

  // 查找是否有重复的属性值
  const isRepeat = attrFormData.attrValueList.some((attrValue) => {
    // 遍历元素就是自己，自己不需要和自己比较
    if (attrValue === row) return false;
    if (attrValue.valueName === row.valueName) return true;
    return false;
  });

  if (isRepeat) {
    ElMessage.warning("不能输入重复的属性值");
    return;
  }

  row.isShowEdit = false;
};

// 切换到编辑模式
const switchEdit = async (row: AttrValueItem) => {
  row.isShowEdit = true;
  // 之前不需要nextTick，是因为v-show，隐藏时input元素还在，所以可以直接操作
  // 现在v-if，隐藏时input被卸载了，所以需要nextTick
  await nextTick();
  // 让input获取焦点
  inputRef.value.focus();
};

// 删除属性值
const delAttrValue = (index: number) => {
  attrFormData.attrValueList.splice(index, 1);
};

const emit = defineEmits(["setIsShowAttrList"]);

const cancel = () => {
  emit("setIsShowAttrList", true);
};
</script>

<style scoped>
.attr__input {
  width: 200px;
}
</style>
